package com.hznu.ez4life.modules.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hznu.ez4life.modules.entity.User;
import com.hznu.ez4life.modules.service.LoginService;
import com.hznu.ez4life.modules.service.UserService;
import com.hznu.ez4life.myBeans.CodeToSession;
import com.hznu.ez4life.myBeans.ConfigParameters;
import com.hznu.ez4life.myBeans.LoginInfo;
import org.aspectj.apache.bcel.classfile.Code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    ConfigParameters configParameters;
    @Autowired
    UserService userService;

    @Override
    public String create3rdSession(String code,HttpServletRequest httpServletRequest)
    {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+configParameters.getAppid()+
                "&secret="+configParameters.getAppsecret()+
                "&js_code="+code+
                "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> entity1 = restTemplate.getForEntity(url,String.class);
        CodeToSession codeToSession = JSONObject.parseObject(entity1.getBody(),CodeToSession.class);
        String openid = codeToSession.getOpenid();
        String session_key = codeToSession.getSession_key();
        HttpSession httpSession = httpServletRequest.getSession();
        httpSession.setAttribute("openid",openid);
        httpSession.setAttribute("session_key",session_key);
        return httpSession.getId();
    }

//    @Override
//    public LoginInfo onLogin(User user,String code, HttpServletRequest httpServletRequest)
//    {
//        CodeToSession codeToSession = create3rdSession(code);
//        String openid = codeToSession.getOpenid();
//        String session_key = codeToSession.getSession_key();
//        HttpSession httpSession = httpServletRequest.getSession();
//        httpSession.setAttribute("openid",openid);
//        httpSession.setAttribute("session_key",session_key);
//        LoginInfo loginInfo = new LoginInfo();
//        loginInfo.setSessionid(httpSession.getId());
//        loginInfo.setUser(userService.bindUser(openid,user));
//        return loginInfo;
//    }

}
